package com.um.swing.common.util;

import com.um.swing.bean.ImageItem;

import java.awt.*;

public class MathUtils {

    /**
     * 二维空间点到直线垂足计算公式推导及Java实现
     * 原文链接：https://blog.csdn.net/jjwwwww/article/details/83830981830981
     *
     * @param p1 直线
     * @param p2 直线
     * @param p3 点
     * @return
     */
    public static Point getFoot(Point p1, Point p2, Point p3) {
        Point foot = new Point();

        float dx = p1.x - p2.x;
        float dy = p1.y - p2.y;

        float u = (p3.x - p1.x) * dx + (p3.y - p1.y) * dy;
        u /= dx * dx + dy * dy;

        foot.x = (int) (p1.x + u * dx);
        foot.y = (int) (p1.y + u * dy);

        return foot;
    }

    public static Double getAngle(Point p1, Point p2) {
        return getAngle(p1.getX(), p1.getY(), p2.getX(), p2.getY());
    }


    /**
     * 计算一条线的角度
     *
     * @param startX
     * @param startY
     * @param endX
     * @param endY
     * @return
     */
    public static Double getAngle(double startX, double startY, double endX, double endY) {
        Double tempNum;
        if (startY < endY) {
            tempNum = startY;
            startY = endY;
            endY = tempNum;

            tempNum = startX;
            startX = endX;
            endX = tempNum;

            tempNum = null;
        }

        Double angle = Math.toDegrees(Math.atan2(startY - endY, startX - endX));
        if (angle < 0) {
            angle += 360;
        }
        return angle;
    }


    /**
     * 获取两条直线相交的点
     */
    public static Point getIntersectPoint(Point p1, Point p2, Point p3, Point p4) {

        double A1 = p1.getY() - p2.getY();
        double B1 = p2.getX() - p1.getX();
        double C1 = A1 * p1.getX() + B1 * p1.getY();

        double A2 = p3.getY() - p4.getY();
        double B2 = p4.getX() - p3.getX();
        double C2 = A2 * p3.getX() + B2 * p3.getY();

        double det_k = A1 * B2 - A2 * B1;

        if (Math.abs(det_k) < 0.00001) {
            return null;
        }

        double a = B2 / det_k;
        double b = -1 * B1 / det_k;
        double c = -1 * A2 / det_k;
        double d = A1 / det_k;

        double x = a * C1 + b * C2;
        double y = c * C1 + d * C2;

        return new Point((int) x, (int) y);
    }

    public static boolean point4IsLeft(ImageItem prvItem) {
        Point p1 = prvItem.getPointMapItem(ImageItem.P1);
        Point p2 = prvItem.getPointMapItem(ImageItem.P2);
        Point p3 = prvItem.getPointMapItem(ImageItem.P3);
        Point p4 = prvItem.getPointMapItem(ImageItem.P4);

        Point targetP = p3.y - p1.y > p4.y - p1.y ? p4 : p3;
        return targetP.x < p1.x;
    }
}
